package org.luxor.commons.security.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.luxor.commons.core.utils.SpringContextUtils;
import org.luxor.commons.core.utils.StringUtils;
import org.luxor.commons.core.web.controller.BaseRestController;
import org.luxor.commons.core.web.data.R;
import org.luxor.commons.security.entity.AuthenticationSuccessDto;
import org.luxor.commons.security.utils.TokenUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 系统身份认证
 *
 * @author Mark @date 2020-07-26 14:21:10
 */
@Controller
@Api(tags = "系统登陆与登出")
public class SysAuthenticationController extends BaseRestController {

    @ApiOperation(value = "登陆")
    @PostMapping("/login")
    public ResponseEntity<AuthenticationSuccessDto> login(@ApiParam(value = "账号", required = true) @RequestParam String username,
                                                          @ApiParam(value = "密码", required = true) @RequestParam String password) {
        return getSuccess(R.ok(new AuthenticationSuccessDto(TokenUtils.toToken(username), 0)));
    }

    @ApiOperation(value = "登出")
    @GetMapping("/logout")
    public ResponseEntity<ResponseEntity> logout(@ApiParam(value = "身份凭证(token)", required = true) @RequestParam String token) {
        TokenStore tokenStore = SpringContextUtils.getBean(TokenStore.class);
        if (StringUtils.isNotBlank(token) && tokenStore != null) {
            removeAccessToken(token);
        }
        return getSuccess(R.ok("退出成功 bye"));
    }

    protected void removeAccessToken(String tokenValue) {
        TokenStore tokenStore = SpringContextUtils.getBean(TokenStore.class);
        if (tokenStore == null) {
            return;
        }
        OAuth2AccessToken token = tokenStore.readAccessToken(tokenValue);
        if (token != null && StringUtils.isNotBlank(token.getValue())) {
            // 清空access token
            tokenStore.removeAccessToken(token);

            OAuth2RefreshToken refreshToken = token.getRefreshToken();
            if (refreshToken != null && StringUtils.isNotBlank(refreshToken.getValue())) {
                // 清空 refresh token
                tokenStore.removeRefreshToken(refreshToken);
            }
        }
    }
}
